from common.models.cart import MemberCart
from common.libs.Helper import getCurrentDate

class CartService:
    @staticmethod
    def delItem(member_id, item_list):
        """
        删除购物车
        :param member_id:
        :param item_list:
        :return:
        """
        if not item_list or member_id < 1:
            return False

        for item in item_list:
            food_id = item['id']
            cart_info = MemberCart.query.filter_by(
                member_id=member_id, food_id=food_id
            ).first()
            cart_info.delete()
        return True


    @staticmethod
    def setItem(member_id=0, food_id=0, change_number=0):
        """
        加入购物车
        :param member_id:
        :param food_id:
        :param change_number:
        :return:
        """
        if member_id < 1 and food_id < 1:
            return False

        cart_info = MemberCart.query.filter_by(
            member_id=member_id, food_id=food_id
        ).first()

        if cart_info:  # 修改
            model_cart = cart_info
            model_cart.quantity = model_cart.quantity + change_number
        else:  # 添加
            model_cart = MemberCart()
            model_cart.member_id = member_id
            model_cart.quantity = change_number
            model_cart.created_time = getCurrentDate()

        model_cart.food_id = food_id
        model_cart.updated_time = getCurrentDate()
        model_cart.save()

        return True
